'use strict'

define(['jquery', 'bootstrap', 'validate', 'validate.en', 'shiftform'], function($, validate) {
  
  return {
    
    init: function() {
      
      this.initPage();
      this.setup();
      this.print();
      this.close();
      
    },
    
    initPage: function() {
      
      var that = this;
      
      $(document).on('click', 'input[name="select-all"]', function(e){
        var checked  = $('input[name="select-all"]').prop('checked');
        $('input[name="dispatchOrderId"]').prop('checked', checked);
      });

      
      $(document).on("click", "a[data-target='#reimburse-setup']", function(e){
        e.preventDefault();
        
        if($('input[name="dispatchOrderId"]:checked').length == 0) {
          $(".invalid-message").removeClass("hide");
        } else {
          var paramsArray = [];
          $("input:checkbox[name=dispatchOrderId]:checked").each(function(){
            paramsArray.push($(this).val());
          });
          var url = $(this).data("url") + "?dispatchOrderIds=" + paramsArray.join(",");
          url = decodeURIComponent(url);
          $(this).attr("href", url).trigger('open.bs.modal');
          $(".invalid-message").addClass("hide");
        }
      })
      
      $('input[name="dispatchOrderId"]').on("change", function(e){
        e.preventDefault();
        if($('input[name="dispatchOrderId"]:checked').length > 0) {
          $(".invalid-message").addClass("hide");
          $("a[data-target='#reimburse-setup']").removeClass("disabled");
          $("a[data-target='#oil-price-print']").removeClass("disabled");
          $("a[data-target='#reimburse-print']").removeClass("disabled");
        }
      })
      
    },
    
    setup: function() {
      
      var that = this;
      
      $(document).on("shown.bs.modal", "#reimburse-setup", function (e) {
        
        // 1. 前置校验
        $('input[name="dispatchOrderId"]:checked').each(function() {
          var reimbursed = $(this).data('reimbursed');
          if (reimbursed) {
            
            $('#check-info-div').css({'display': ''});
            $('#check-info-label').text('已报销派车单不能再次设置内部油量').css({'color': 'red'});
            
            valid = false;
            $(e.currentTarget).find('button[type="btn-set-export"]').addClass('disabled');
            
          }
        });
        
        var $form = $(e.currentTarget).find("form");
        
        $form.shiftform({
          needLoad: false,
          beforeSubmit: function() {
            var ratedOilUsage = $('input[name="ratedOilUsage"]').val();
            var actualOilUsage = $('input[name="actualOilUsage"]').val();

            if (actualOilUsage === null || actualOilUsage.trim() === "") {
              $('#check-info-div').css({'display': ''});
              $('#check-info-label').text('实际加油量不能为空').css({'color': 'red'});
              return false;
            }
            
            if(isNaN(actualOilUsage)) {
              $('#check-info-div').css({'display': ''});
              $('#check-info-label').text('请输入有效数字').css({'color': 'red'});
              return false;
            }
            
            if (Number(actualOilUsage) > Number(ratedOilUsage)) {
              $('#check-info-div').css({'display': ''});
              $('#check-info-label').text('实际加油量不能超过额定加油量').css({'color': 'red'});
              return false;
            }
            
            var reg = /^[0-9]{1}\d*(\.\d{1,2})?$/;
            if (!reg.test(actualOilUsage)) {
              $('#check-info-div').css({'display': ''});
              $('#check-info-label').text('输入数字不合法').css({'color': 'red'});
              return false;
            }
            
            return true;
            
          }, success: function(el, backdrop, message, data) {
            
            var paramsArray = [];
            $("input:checkbox[name=dispatchOrderId]:checked").each(function(){
              if(!$(this).data("expenseprint")) {
                paramsArray.push($(this).val());
              }
            });
            
            $(backdrop).find('p').html('<strong>' + message + '</strong>').addClass('text-success')
            $($(el).parents(".modal")).modal('hide');
            
            var currentUrl = window.location.href.split("&selectDispatchOrderId=")[0] + "&selectDispatchOrderId=" + paramsArray.join(",");
            setTimeout(function(){
              window.location.href = currentUrl;
            }, 500)
          }
        })
        
      });
    },
    
    print: function() {
      
      $(document).on('shown.bs.modal', '#reimburse-print, #oil-price-print', function(e) {
        
        var $form = $(e.currentTarget).find("form");
        $("input[name='dispatchOrderId']:checked").each(function(){
          var inputHtml = "<input type='hidden' name='dispatchOrderIds' value='"+$(this).val()+"' />";
          $form.append(inputHtml);
        })
        
      });
      
    },
    
    close: function() {
      $(document).on('click', 'button[name="cancel-redirect"]', function(e) {
        e.preventDefault();
        window.location.reload();
      });
    }
    
  }
})